#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "../inc/data.h"
#include "../inc/flight_node.h"
#include "../inc/general.h"
#include "../inc/user_node.h"
#include "../inc/user.h"
#include "../inc/my_flight_node.h"

// 显示所有航班信息---用户
void find_flightInfo(flight_Node_p headNode)
{
    const int pageSize = 5; // 每页显示5条记录
    int currPage = 1;
    flight_Node_p currNode = headNode->next;
    int size = 0;
    do
    {
        clearScreen();
        int total = getFlightCount(headNode);
        int totalPages = (total + pageSize - 1) / pageSize;
        printf("                          查询航班信息(第%d页/共%d页)\n", currPage, totalPages);
        print_Lines();
        printf("共有%d 个航班信息,信息如下:\n", total);
        print_Lines2();
        printf("序号:  航班公司     航班号\t起飞地->目的地\t    起飞时间\t       剩余票\n");
        print_Lines2();
        int count = 0;
        int index = 1;
        // int index = 1 + (currPage - 1) * pageSize;
        flight_Node_p pageStart = currNode; // 保存当前页起始节点

        while (currNode != headNode && count < pageSize)
        {
            printf(" %2d    %s     %4s       %4s->%4s\t%s %s\t%3d\n",
                   index,
                   currNode->data->airline,
                   currNode->data->flight_id,
                   currNode->data->start,
                   currNode->data->end,
                   currNode->data->date,
                   currNode->data->time,
                   seatOrRemainder_num(currNode, 1));
            index++;
            print_Lines();
            count++;
            currNode = currNode->next;
        }
        printf("指令: (序号)详细信息 (F)查询条件 (A)上一页 (D)下一页 (Q)退出: ");
        // 翻页
        while (1)
        {
            char input;
            scanf(" %c", &input);
            clearChar();
            int index = input - '0';
            if (total >= pageSize)
            {
                if (currPage * pageSize >= total)
                {
                    size = total - (currPage - 1) * pageSize; // 最后一页
                }
                else
                {
                    size = pageSize; // 中间页
                }
            }
            else
            {
                size = total;
            }
            if (index >= 1 && index <= size)
            {
                flight_Node_p findNode = pageStart;
                for (int i = 0; i < (index - 1) % pageSize; i++)
                    findNode = findNode->next;
                show_FindDetailFlight(findNode);
                currNode = pageStart;
                break;
            }

            if (input == 'F' || input == 'f')
            {
                find_flightInfo_temp(pageStart, pageSize, total, currPage);
                searchFlight(headNode);
                currNode = pageStart;
                clearScreen();
                break;
            }
            if (input == 'a' || input == 'A')
            {
                if (currPage > 1)
                {
                    flight_Node_p newStart = pageStart;
                    for (int i = 0; i < pageSize && newStart->prev != headNode; i++)
                    {
                        newStart = newStart->prev;
                    }
                    if (newStart != pageStart)
                    { // 确认指针已移动
                        currNode = newStart;
                        currPage--;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是第一页了,请按D移到下一页:");
                }
            }

            else if (input == 'd' || input == 'D')
            {
                if (currPage < totalPages)
                {
                    if (currNode != headNode)
                    { // 确保没有越界
                        currPage++;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是最后一页了,请按A移到上一页:");
                }
            }
            else if (input == 'q' || input == 'Q')
            {
                return;
            }
            else
            {
                printf("输入错误,请重新输入:");
            }
        }
    } while (1);
}

// 显示航班信息(临时)
void find_flightInfo_temp(flight_Node_p headNode, int pageSize, int total, int currPage)
{
    clearScreen();
    int totalPages = (total + pageSize - 1) / pageSize; // 计算总页数

    flight_Node_p currNode = headNode;

    printf("                          查询航班信息(第%d页/共%d页)\n", currPage, totalPages);
    print_Lines();
    printf("共有%d 个航班信息,信息如下:\n", total);
    print_Lines2();
    printf("序号:  航班公司     航班号\t起飞地->目的地\t    起飞时间\t       剩余票\n");
    print_Lines2();
    int count = 0;
    int index = 1;
    if (total < pageSize)
    {
        pageSize = total;
    }
    while (currNode != NULL && count < pageSize)
    {
        printf(" %2d    %s     %4s       %4s->%4s\t%s %s\t%3d\n",
               index,
               currNode->data->airline,
               currNode->data->flight_id,
               currNode->data->start,
               currNode->data->end,
               currNode->data->date,
               currNode->data->time,
               seatOrRemainder_num(currNode, 1));
        index++;
        print_Lines();
        count++;
        currNode = currNode->next;
    }
}

// 选择查询条件
void searchFlight(flight_Node_p headNode)
{
    printf("[1] 航班号 [2] 起始地 [3] 目的地 [4] 日期 [5] 时间 [6] 价格 [Q] 返回\n");
    printf("请指定查询条件：");
    while (1)
    {
        char input;
        scanf(" %c", &input);
        clearChar();
        flight_Node_p resultNode = NULL;
        switch (input)
        {
        case '1':
            flight_Node_p currNode = find_flightByNo(headNode);
            if (currNode != NULL)
                show_FindDetailFlight(currNode);
            return;
        case '2':
            resultNode = find_flightByStart(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            find_flightInfo(resultNode);
            free_flightList(resultNode);
            return;
        case '3':
            resultNode = find_flightByEnd(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            find_flightInfo(resultNode);
            free_flightList(resultNode);
            return;
        case '4':
            resultNode = find_flightByDate(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            find_flightInfo(resultNode);
            free_flightList(resultNode);
            return;
        case '5':
            resultNode = find_flightByTime(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            find_flightInfo(resultNode);
            free_flightList(resultNode);
            return;
        case '6':
            resultNode = find_flightByPrice(headNode);
            if (resultNode == NULL)
            {
                return;
            }
            find_flightInfo(resultNode);
            free_flightList(resultNode);
            return;
        case 'Q':
        case 'q':
            return;
        default:
            printf("输入错误，请重新输入：");
            break;
        }
    }
}

// 显示航班详细信息
int show_FindDetailFlight(flight_Node_p currNode)
{
    int mark = 0;
    while (1)
    {
        my_flight_Node_p m_currNode = find_my_flight_byUsernameAndFlightID(myflight_headNode, Login_Username, currNode->data->flight_id);
        flight_p flight = currNode->data;
        clearScreen();
        printf("                                             航班详细信息\n");
        printf("-------------------------------------------------------------------------------------------------------------\n");
        printf("航班信息为:\t\t\t\t\t\t");
        printf("航班座位及票价信息:\n");
        printf("===================================\t\t\t");
        printf("===================================================\n");
        printf("航空公司:\t%s\t\t\t\t", flight->airline);
        printf("\t商务舱\t一等舱\t经济舱\t头等舱\t公务舱\n");

        printf("-----------------------------------\t\t\t");
        printf("===================================================\n");
        printf("航班号:\t\t%s\t\t\t\t\t", flight->flight_id);
        printf("票价:\t%d\t%d\t%d\t%d\t%d\n", flight->price[0], flight->price[1], flight->price[2], flight->price[3], flight->price[4]);
        printf("-----------------------------------\t\t\t");
        printf("---------------------------------------------------\n");
        printf("航线:\t\t%s->%s\t\t\t\t", flight->start, flight->end);
        printf("余票:\t%d\t%d\t%d\t%d\t%d\n", flight->remainder[0], flight->remainder[1], flight->remainder[2], flight->remainder[3], flight->remainder[4]);
        printf("----------------------------------\t\t\t");
        printf("===================================================\n");
        printf("起飞时间:\t%s %s\t\t\t\n", flight->date, flight->time);
        if (m_currNode != NULL)
        {
            printf("===================================\t\t\t");
            printf("您预定的位置为: %s ,票价为: %d\n", flight_index_to_type(m_currNode->data->seat_type), m_currNode->data->price);
        }
        else
        {
            printf("===================================\t\t\t");
            printf("欢迎光临,请选择您的位置!\n");
        }
        printf("-------------------------------------------------------------------------------------------------------------\n");
        if (m_currNode != NULL)
        {
            if (m_currNode->data->status == 1)
                printf("指令: (Q)返回上一级:");
            else if (m_currNode->data->status == 0)
                printf("指令: (1) 航班预定 (2)取消预订 (Q)返回上一级:");
        }
        else
            printf("指令: (1) 航班预定 (Q)返回上一级:");
        char input;
        scanf(" %c", &input);
        switch (input)
        {
        case '1':
            show_FindDetailFlight_temp(currNode, m_currNode);
            scheduled_flight(currNode);
            break;
        case '2':
            show_FindDetailFlight_temp(currNode, m_currNode);
            Cancel_Flight(currNode);
            mark = 2;
            break;
        case 'Q':
        case 'q':
            clearScreen();
            return mark;
        default:
            printf("输入错误,请重新输入!\n");
        }
    }
}

// 显示航班详细信息(临时)
void show_FindDetailFlight_temp(flight_Node_p currNode, my_flight_Node_p m_currNode)
{
    flight_p flight = currNode->data;
    clearScreen();
    printf("                                             航班详细信息\n");
    printf("-------------------------------------------------------------------------------------------------------------\n");
    printf("航班信息为:\t\t\t\t\t\t");
    printf("航班座位及票价信息:\n");
    printf("===================================\t\t\t");
    printf("===================================================\n");
    printf("航空公司:\t%s\t\t\t\t", flight->airline);
    printf("\t商务舱\t一等舱\t经济舱\t头等舱\t公务舱\n");

    printf("-----------------------------------\t\t\t");
    printf("===================================================\n");
    printf("航班号:\t\t%s\t\t\t\t\t", flight->flight_id);
    printf("票价:\t%d\t%d\t%d\t%d\t%d\n", flight->price[0], flight->price[1], flight->price[2], flight->price[3], flight->price[4]);
    printf("-----------------------------------\t\t\t");
    printf("---------------------------------------------------\n");
    printf("航线:\t\t%s->%s\t\t\t\t", flight->start, flight->end);
    printf("余票:\t%d\t%d\t%d\t%d\t%d\n", flight->remainder[0], flight->remainder[1], flight->remainder[2], flight->remainder[3], flight->remainder[4]);
    printf("----------------------------------\t\t\t");
    printf("===================================================\n");
    printf("起飞时间:\t%s %s\t\t\t\n", flight->date, flight->time);
    if (m_currNode != NULL)
    {
        printf("===================================\t\t\t");
        printf("您预定的位置为: %s ,票价为: %d\n", flight_index_to_type(m_currNode->data->seat_type), m_currNode->data->price);
    }
    else
    {
        printf("===================================\t\t\t");
        printf("欢迎光临,请选择您的位置!\n");
    }
    printf("-------------------------------------------------------------------------------------------------------------\n");
}

// 预定航班
void scheduled_flight(flight_Node_p currNode)
{
    int seat_type = -1;
    if (find_my_flight_byUsernameAndFlightID(myflight_headNode, Login_Username, currNode->data->flight_id) != NULL)
    {
        printf("您已经预定过该航班了!\n");
        waitForAnyKey();
        return;
    }
    printf("请输入您要预定的舱位 [0] 商务舱 [1] 一等舱 [2] 经济舱 [3] 头等舱 [4] 公务舱 [Q]返回:");
    char input;
    scanf(" %c", &input);
    clearChar();
    if (input != '0' && input != '1' && input != '2' && input != '3' && input != '4' && input != 'Q' && input != 'q')
    {
        printf("\n无效选择,请输入0-4之间的数字1\n");
        waitForAnyKey();
        return;
    }
    else if (input == 'Q' || input == 'q')
    {
        clearScreen();
        return;
    }
    seat_type = get_seat_type(input);
    if (currNode->data->seat[seat_type] == 0)
    {
        printf("\n该舱位已满,请选择其他舱位\n");
        waitForAnyKey();
        return;
    }
    user_Node_p currUser = find_userNode(user_headNode, Login_Username);
    int price, fuel_fee, airport_tax; // 总价格 燃油费  机场建设费
    for (int i = 0; i < sizeof(airline) / sizeof(airline[0]); i++)
    {
        if (strcmp(currNode->data->airline, airline[i].airline) == 0)
        {
            fuel_fee = airline[i].fuel_fee;
            airport_tax = airline[i].airport_tax;
            break;
        }
    }
    price = currNode->data->price[seat_type] + fuel_fee + airport_tax;
    if (currUser->data->money < price)
    {
        printf("\n费用为机票+燃油费+机场建设费= %d + %d + %d ,您的余额不足 %d ,请充值!\n", currNode->data->price[seat_type], fuel_fee, airport_tax, price);
        waitForAnyKey();
        return;
    }
    printf("\n您预定的航班为: %s ,航舱为: %s\n费用为机票+燃油费+机场建设费= %d + %d + %d = %d ,您当前余额为：%d\n请确认是否购买(y/n)\n",
           currNode->data->flight_id, flight_index_to_type(seat_type), currNode->data->price[seat_type], fuel_fee, airport_tax, price, currUser->data->money);
    if (if_goOn() == -1)
    {
        printf("取消成功!\n");
        waitForAnyKey();
        return;
    }
    currNode->data->remainder[seat_type]--;

    my_flight_p newflight = (my_flight_p)malloc(sizeof(my_flight_t));
    strcpy(newflight->username, Login_Username);
    strcpy(newflight->airline, currNode->data->airline);
    strcpy(newflight->flight_id, currNode->data->flight_id);
    newflight->seat_type = seat_type;
    newflight->price = price;
    newflight->status = 0;

    my_flight_insert(myflight_headNode, newflight);
    currUser->data->money -= price;

    printf("预定成功!感谢您选择我们的服务!\n");
    waitForAnyKey();
}

// 取消航班
void Cancel_Flight(flight_Node_p currNode)
{
    my_flight_Node_p cancelNode = find_my_flight_byUsernameAndFlightID(myflight_headNode, Login_Username, currNode->data->flight_id);
    if (cancelNode == NULL)
    {
        printf("您没有预定该航班!\n");
        waitForAnyKey();
        return;
    }
    printf("您确定要取消航班吗?(Y/N)\n");
    if (if_goOn() == -1)
    {
        printf("已保留您的航班预定!\n");
        waitForAnyKey();
        return;
    }

    int fuel_fee, airport_tax, Penalty; // 燃油费 机场建设费 违约金
    for (int i = 0; i < sizeof(airline) / sizeof(airline[0]); i++)
    {
        if (strcmp(currNode->data->airline, airline[i].airline) == 0)
        {
            fuel_fee = airline[i].fuel_fee;
            airport_tax = airline[i].airport_tax;
            Penalty = airline[i].Penalty;
            break;
        }
    }
    int base_price = cancelNode->data->price - fuel_fee - airport_tax;
    int penalty_fee = base_price / Penalty;
    int refund_amount = cancelNode->data->price - penalty_fee;
    printf("取消费用明细:\n");
    printf("--------------------\n");
    printf("机票原价: %d\n", cancelNode->data->price);
    printf("燃油附加费: %d\n", fuel_fee);
    printf("机场建设费: %d\n", airport_tax);
    printf("违约金(%d%%): %d\n", Penalty, penalty_fee);
    printf("--------------------\n");
    printf("实际退款: %d\n", refund_amount);
    printf("请再次确认是否取消该航班?(Y/N)\n");
    if (if_goOn() == -1)
    {
        printf("已保留您的航班预定!\n");
        waitForAnyKey();
        return;
    }
    else
    {
        printf("已取消该航班预定!\n");
        user_Node_p currUser = find_userNode(user_headNode, Login_Username);
        currUser->data->money += refund_amount;
        my_flight_delete(cancelNode);
        waitForAnyKey();
        return;
    }
}

int get_seat_type(char input)
{
    switch (input)
    {
    case '0':
        return 0;
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    default:
        return -1;
    }
}

void print_user_flight(my_flight_Node_p headNode)
{
    my_flight_Node_p myFlight = get_userFlightList(headNode, Login_Username);
    const int pageSize = 5; // 每页显示5条记录
    int currPage = 1;
    int size = 0;
    do
    {
        my_flight_Node_p currNode = myFlight->next;
        clearScreen();
        int total = getMyFlightCount(myFlight);
        int totalPages = (total + pageSize - 1) / pageSize;
        if (myFlight->next == myFlight)
        {
            printf("您还没有预定任何航班!\n");
            waitForAnyKey();
            return;
        }
        printf("                                     我的航班(第%d页/共%d页)\n", currPage, totalPages);
        print_Lines5();
        printf("共有%d 个航班信息,信息如下:\n", total);
        print_Lines6();
        printf("序号:  航班公司     航班号\t起飞地->目的地\t    起飞时间\t       票价\t座位类型    状态\n");
        print_Lines6();
        int count = 0;
        int index = 1;
        my_flight_Node_p pageStart = currNode; // 保存当前页起始节点

        while (currNode != myFlight && count < pageSize)
        {
            flight_Node_p dataNode = find_flightByflight_id(flight_headNode, currNode->data->flight_id);
            printf(" %2d    %s     %s       %s->%s\t%s %s       %d      %s    ",
                   index,
                   dataNode->data->airline,
                   dataNode->data->flight_id,
                   dataNode->data->start,
                   dataNode->data->end,
                   dataNode->data->date,
                   dataNode->data->time,
                   currNode->data->price,
                   flight_index_to_type(currNode->data->seat_type));
            if (currNode->data->status == 1)
            {
                printf(COLOR_BLUE "%s\n" COLOR_RESET, get_status(currNode->data->status));
            }
            else
            {
                printf(COLOR_GREEN "%s\n" COLOR_RESET, get_status(currNode->data->status));
            }

            index++;
            print_Lines5();
            count++;
            currNode = currNode->next;
        }
        printf("指令: (序号)详细信息 (A)上一页 (D)下一页 (Q)退出: ");
        // 翻页
        while (1)
        {
            char input;
            scanf(" %c", &input);
            while (getchar() != '\n')
                ; // 清空输入缓冲区
            int index = input - '0';
            if (total >= pageSize)
            {
                if (currPage * pageSize >= total)
                {
                    size = total - (currPage - 1) * pageSize; // 最后一页
                }
                else
                {
                    size = pageSize; // 中间页
                }
            }
            else
            {
                size = total;
            }
            if (index >= 1 && index <= size)
            {
                my_flight_Node_p findNode = pageStart;
                for (int i = 0; i < (index - 1) % pageSize; i++)
                    findNode = findNode->next;
                int state = show_FindDetailFlight(find_flightByflight_id(flight_headNode, findNode->data->flight_id));
                if (state == 2)
                {
                    // 回到第一页
                    currPage = 1;
                    myFlight = get_userFlightList(headNode, Login_Username);
                    currNode = myFlight->next;
                }
                else
                {
                    currNode = pageStart;
                }
                break;
            }
            if (input == 'a' || input == 'A')
            {
                if (currPage > 1)
                {
                    my_flight_Node_p newStart = pageStart;
                    for (int i = 0; i < pageSize && newStart->prev != headNode; i++)
                    {
                        newStart = newStart->prev;
                    }
                    if (newStart != pageStart)
                    { // 确认指针已移动
                        currNode = newStart;
                        currPage--;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是第一页了,请按D移到下一页:");
                }
            }
            else if (input == 'd' || input == 'D')
            {
                if (currPage < totalPages)
                {
                    if (currNode != headNode)
                    { // 确保没有越界
                        currPage++;
                        clearScreen();
                        break;
                    }
                }
                else
                {
                    printf("已经是最后一页了,请按A移到上一页:");
                }
            }
            else if (input == 'q' || input == 'Q')
            {
                return;
            }
            else
            {
                printf("输入错误,请重新输入:");
            }
        }

    } while (1);
    free_my_flightList(myFlight);
}
